<?php

define("DEV", true);
define("CASCADE", "cascade/");
define("INCLUDES", CASCADE . "includes/");
define("PLUGINS", CASCADE . "plugins/");
define("TEMPLATES", CASCADE . "templates/");
define("CACHE", CASCADE . "cache/");
define("WEBROOT", str_replace(basename(__FILE__), "", $_SERVER["PHP_SELF"]));

function permanentRedirect($url) {
	header("HTTP/1.1 301 Moved Permanently");
	header("Location: $url");
	exit;
}

function pageNotFound($message = null) {
	header("HTTP/1.1 404 Page Not Found");
	readfile(TEMPLATES . "404.html");
	
	if ($message && DEV)
		echo "<font style='font-weight:bold;color:red'>$message</font>";
	exit;
}


// get request data
$useWWW = false;
$hasWWW = 0;
$server = preg_replace('/^www\./', "", $_SERVER["HTTP_HOST"], -1, $hasWWW);

// take off first slash and ending slash or .html
$request = preg_replace('~^/|(/|\.\w+)?(\?.*)?$~', "", $_SERVER["REQUEST_URI"]);

if (!$useWWW && $hasWWW)
	permanentRedirect("http://$server" . $_SERVER["REQUEST_URI"]);
elseif ($useWWW && !$hasWWW)
	permanentRedirect("http://www.$server" . $_SERVER["REQUEST_URI"]);

$path = $request ? "$server/$request" : $server;

$isAdmin = strpos($_SERVER["HTTP_USER_AGENT"], "Cascade") !== false;

if ($isAdmin) {
	session_start();
	// validate here
	if (!$_SESSION["admin"])
		$isAdmin = false;
}

require_once INCLUDES . "blueprint/Blueprint.php";

$BLUEPRINT_TEMPLATES_DIR = TEMPLATES;
$BLUEPRINT_CACHE_DIR = CACHE;
$BLUEPRINT_WEBROOT = preg_replace('|index.php.*$|', "", $_SERVER['PHP_SELF']);

// Show the cached version if it is current
$cache = $BLUEPRINT_CACHE_DIR . $path . ".cache";
if (!DEV && !$isAdmin && CachedTemplate::validCache($cache, 5)) {
	readfile($cache);
	exit;
} elseif (DEV) {
	@unlink($cache);
}

// load needed libraries to show the page
require_once INCLUDES . "connections.php";
require_once INCLUDES . "Page.php";
require_once INCLUDES . "Revision.php";
require_once INCLUDES . "Template.php";
require_once INCLUDES . "Field.php";
require_once INCLUDES . "blueprint/parsing/HTMLDocument.php";

// load up plugins
$plugins = array();
$dir = new DirectoryIterator(PLUGINS);
foreach ($dir as $file) {
	if ($file->isFile()) {
		if (preg_match('/^(\w+)\.php$/', $file->getFilename(), $matches)) {
			$classname = $matches[1];
			require_once $file->getPathname();
			if (class_exists($classname))
				$plugins[] = new $classname();
		}
	}
}

$page = Page::findFirst(array("path = ?", $path));

if (!$page) // TODO, show custom page not found page
	pageNotFound("This page does not exist in the database");

if ($page->redirect_id) {
	$redirectPage = new Page($page->redirect_id);
	permanentRedirect("http://$redirectPage->path");
}

$page->loadRevisions(null, "created");

if ($isAdmin && isset($_GET["draft"])) {
	$revision = $page->revisions[count($page->revisions) - 1];
} else {
	$revision = $page->getRevision(null, $isAdmin);
}

if (!$revision) // TODO, show custom page not found page
	pageNotFound("This page exists but has no published revisions");

$template = $revision->loadTemplate();

if (!$template)
	pageNotFound("The template for this page was not found");

$view = new Blueprint($template->pageFile, $template->layoutFile || $isAdmin ? null : $cache);
$view->assign("page", $page);

if ($template->layoutFile) {
	$layout = new Blueprint($template->layoutFile, $isAdmin ? null : $cache);
	$layout->assign("page", $page);
}

// breadcrumbs
$breadcrumbs = split("/", $path);
array_shift($breadcrumbs);
//array_pop($breadcrumbs);
$view->assign("breadcrumbs", $breadcrumbs);
if ($layout)
	$layout->assign("breadcrumbs", $breadcrumbs);

$fields = $template->loadFields();

if ($isAdmin && isset($_GET["draft"]))
	$page->loadContentsByRevision($revision->id);
else
	$page->loadContents();

foreach ($fields as $field) {
	
	$content = "";
	
	foreach ($page->contents as $contentObj) {
		if ($contentObj->field == $field->name) {
			$content = $contentObj->value;
			break;
		}
	}
	
	if (!$content)
		$content = $field->content;
			
	foreach ($plugins as $plugin) {
		if (method_exists($plugin, "handleContent")) {
			$content = $plugin->handleContent($content);
		}
	}
	
	if ($isAdmin && $field->name != "title")
		$content = "<cms name=\"$field->name\" type=\"$field->type\">$content</cms>";
	
	$view->assign($field->name, $content);
	if ($layout)
		$layout->assign($field, $content);
}

$output = $view->fetch();

if ($layout) {
	$layout->assign("pageContent", $output);
	$output = $layout->fetch();
}

foreach ($plugins as $plugin) {
	if (method_exists($plugin, "handleOutput")) {
		$output = $plugin->handleOutput($output);
	}
}

echo $output;
?>